function creatDom (node, inner, eventType = 'click', callBack) {
    const list = node.split('&')
    const btn = document.createElement(list[0])
    const div = document.createElement('div')
    div.style.padding = '10px'
    if (list[1]) {
        btn.type = list[1]
    }
    btn.innerHTML = inner
    document.body.appendChild(div)
    div.appendChild(btn)
    if (callBack && callBack instanceof Function) {
        btn.addEventListener(eventType, callBack)
    }
}
creatDom('h2', 'fetch === 测试')
creatDom('button', '测试请求接口', 'click', queryFetch)

async function queryFetch () {
    const geturl = 'http://hmajax.itheima.net/api/area'
    const params = new URLSearchParams({ pname: '山西省', cname: '运城市' })
    console.log(params.toString())
    const res = await fetch(geturl + '?' + params.toString())
    console.log('res', res)
    if (res.status >= 200 && res.status < 300) {
        const data = await res.json()
        console.log('data', data)
    } else {
        console.log('请求异常')
    }
}
creatDom('input&file', '上传图片', 'change', uploadImg)

async function uploadImg (params) {
    const uploadUrl = 'http://hmajax.itheima.net/api/uploadimg'
    const img = document.createElement('img')
    document.body.appendChild(img)
    console.log(params.target.files[0])
    const formData = new FormData()
    formData.append('img', params.target.files[0])
    const res = await fetch(uploadUrl, {
        method: 'post',
        body: formData
    })
    console.log(res)
    if (res.status >= 200 && res.status < 300) {
        const { data } = await res.json()
        console.log(data)
        img.src = data.url
    } else {
        console.log('请求异常')
    }

}


creatDom('button', '设置请求头添加json', 'click', update)
async function update (params) {
    const updeteUrl = 'http://hmajax.itheima.net/api/register'
    const headers = new Headers()
    headers.append('Content-Type', 'application/json')
    const data = {
        username: '1231111qq1111',
        password: '123456789'
    }
    fetch(updeteUrl, {
        method: 'post',
        body: JSON.stringify(data),
        headers: headers
    })

}